<?php
/**
 * Created by PhpStorm.
 * User: Anthony
 * Date: 2017/7/27
 * Time: 下午12:59
 */

namespace App\Http\Middleware;

use App\Services\UserService;
use Closure;
use Illuminate\Support\Facades\Redis;

/**
 * 单用户登入中间件
 * 当有其他用户登入，当前用户被T出，并给予一个403页面提示
 *
 * Class SsoMiddleware
 * @package App\Http\Middleware
 */
class SSOMiddleware
{
    protected $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function handle($request, Closure $next)
    {
        if (!auth()->guest()) {
            $userInfo = auth()->user();
            $singleToken = $request->cookie(UserService::SINGLE_KEY);

            if ($singleToken) {
                $redisTime = Redis::get(UserService::SINGLE_KEY . '_' . $userInfo->id);
                $secret = $this->userService->getSingleToken($userInfo->id, $redisTime);

                if (0 !== strcmp($secret, $singleToken)) {
                    $this->userService->setUserLoginOut($request);
                    return response()->view('errors.403', ['exception' => 403], 403);
                }

                return $next($request);
            }
        }
    }
}